import React, { Component } from 'react'
import PropTypes from 'prop-types';
import { Upload, Modal, Icon, message } from 'antd';  
import { connect } from 'dva'
import { dispatch } from 'umi'
import api from '@/api';

let timer = null 
/** 
 * 获取base64文件
 */
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
    })
}

/**
 * 上传组件未上传时展示内容组件
 */
function UploadButton(props){                        
    if(props.files.length>=0 && !props.isEdit){
        return <div style={{ fontSize: '12px' }}>暂未上传</div> 
    }
    return  (
        <div>
            <Icon type="plus" />
            <div style={{ marginTop: 8,fontSize: '12px' }}>上传图片</div>
        </div>
    )       
} 

/**
 * 上传组件
 */
@connect(({infoenterprise})=>( { serviceInfo: infoenterprise.serviceInfo }))
class FUploader extends Component {
    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
    }
    hanldeCustomRequest = (options)=>{
        const { file } = options
        const imgItem = {
            uid: new Date().getTime(),
            name: 'will.png',
            status: 'uploading',
            url: '',
            percent: 1
        }
        let curImgItem = []
        if( this.props.num > 1 && this.props.fileList.length >= 1){
            curImgItem = JSON.parse(JSON.stringify(this.props.fileList))
            curImgItem.push(imgItem)
            this.props.triggerUrlChange(curImgItem)
        }else{
            this.props.triggerUrlChange([imgItem])
        }
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (file) => {
            const params = {
                fileStr: file.target.result, // 本地图片base64编码，调接口，返回图片url
            }
            api.info.uploadImage({
                data: params
            }).then(res => {
                if (res.code === 200) {
                    const imgItem = {
                        uid: new Date().getTime(),
                        name: 'will.png',
                        status: 'done',
                        url: res.data,
                        percent: 100
                    } 
                    if(this.props.num > 1 && this.props.fileList.length >= 1){
                        curImgItem = JSON.parse(JSON.stringify(this.props.fileList))
                        const len = curImgItem.length
                        curImgItem[len-1] = imgItem
                        timer = setTimeout(()=>{
                            this.props.triggerUrlChange(curImgItem)
                        }, 500)
                    }else{
                        timer = setTimeout(()=>{
                            this.props.triggerUrlChange([imgItem])
                        }, 500)
                    }
                }
            }).catch(()=>{
                message.error('系统繁忙，请稍后再试')
                let curItem = JSON.parse(JSON.stringify(this.props.fileList))
                curItem.pop()
                this.props.triggerUrlChange(curItem)
            })
        }
    }
    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        })
    }
    handleChange = ({ file, fileList }) => {
        let curData = JSON.parse(JSON.stringify(fileList))
        if(curData && curData.length >= 2){
            for(let i = 0; i < curData.length; i++){
                if(file.url == curData[i].url){
                    curData.splice(i, 1)
                    break
                }
            }
        }
        if (file.status == 'removed') {
            let obj = curData.length >= 1 ? curData : []
            this.props.triggerUrlChange(obj)
        }
    }
    /**
     * 上传验证格式及大小
    */
    beforeUpload = (file)=> {
        const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
            message.error("只能上传JPG或PNG文件!");
            return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 3;
        if (!isLt2M) {
            message.error("图片大小需小于3MB!");
            return false;
        }
        return isJpgOrPng && isLt2M;
    }
  
    componentWillUnmount(){
        if(timer){
          clearTimeout(timer)
        }
    }
    render() {
        const {isEdit, num, fileList, mul} = this.props
        console.log('prop mul', mul, 'isEdit', isEdit)
        const {previewVisible, previewTitle, previewImage} = this.state
        return (
            <React.Fragment>
                 <Upload
                    action="to-heaven"
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    customRequest={this.hanldeCustomRequest}
                    showUploadList={{showRemoveIcon: isEdit}}
                    disabled={!isEdit}
                    beforeUpload={this.beforeUpload}
                >   
                    {
                        (fileList.length >= num || (mul && !isEdit)) ? null : <UploadButton isEdit={isEdit} files={fileList}/>                      
                    }
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="example" style={{ width: '100%' }} src={previewImage}/>
                </Modal>
            </React.Fragment>           
        )
    }
}

FUploader.propTypes = {
    fileList: PropTypes.array,
    triggerUrlChange:PropTypes.func,
    isEdit:PropTypes.bool,
    num: PropTypes.number,
    mul: PropTypes.bool
}
FUploader.defaultProps = {
    num: 1
}

export default FUploader;